import hashlib
import json
import time

from django.shortcuts import render, redirect, HttpResponse
from django.urls import reverse

from .utils.customer_utile import page_utile
from .models import Department, User, UserModelForm, Emp, EmpModelForm
from django.http import JsonResponse


# Create your views here.
# 查询部门列表
def dept_list(request):
    # 查询所有部门信息
    departments = Department.objects.all()
    return render(request, 'dept/dept.html', context={'departments': departments})


# 新增部门
def dept_add(request):
    if request.method == 'GET':
        # 返回添加部门信息的页面
        return render(request, 'dept/dept_add.html')
    else:
        # 获取数据  添加部门信息到数据库
        dept_name = request.POST.get('dept_name')
        dept_address = request.POST.get('dept_address')
        department = Department(name=dept_name, address=dept_address)
        department.save()
        # 路由反向解析
        path = reverse('dept_list')
        # 数据保存完毕  浏览器再次发送一个请求  /app08/dept/list   redirect    重定向   浏览器的行为
        return redirect(path)


def dept_edit(request, id):
    if request.method == 'GET':
        department = Department.objects.filter(id=id).first()
        return render(request, 'dept/dept_edit.html', context={'department': department})
    else:
        dept_name = request.POST.get('dept_name')
        dept_address = request.POST.get('dept_address')
        Department.objects.filter(id=id).update(name=dept_name, address=dept_address)
        # 重定向页面
        return redirect(reverse('dept_list'))


# /app08/dept/edit?id=1          /app08/dept/1
def dept_delete(request, id):
    Department.objects.filter(id=id).delete()
    return redirect(reverse('dept_list'))


# 用户列表
def user_list(request):
    users = User.objects.all()
    return render(request, 'user/user.html', context={'users': users})


"""
#添加数据的传统方案
def user_add(request):
    if request.method == 'GET':
        depts = Department.objects.all()
        context = {
            'depts': depts,
            'genders': User.gender_choices
        }
        return render(request, 'user/user_add.html', context=context)

    # 获取数据  添加用户信息
    username = request.POST.get('username')
    age = request.POST.get('age')
    gender = request.POST.get('gender')
    dept_id = request.POST.get('dept_id')
    # 设置默认密码   111111   摘要算法
    password = hashlib.md5('111111'.encode('utf-8')).hexdigest()
    User.objects.create(username=username, age=age, gender=gender, department_id=dept_id, password=password)
    # 重定向到用户列表
    return redirect(reverse('user_list'))
"""


def user_add(request):
    if request.method == 'GET':
        # 创建一个用户表单对象
        form = UserModelForm()
        return render(request, 'user/user_add.html', context={'form': form})

    # 参数接收
    form = UserModelForm(data=request.POST)
    # 在form中添加一个密码  password
    form.instance.password = hashlib.md5('111111'.encode('utf-8')).hexdigest()
    # 校验参数
    if form.is_valid():
        # 保存数据
        form.save()
        # 添加成功  重定向页面到用户列表页
        return redirect(reverse('user_list'))
    #  数据不合法
    return render(request, 'user/user_add.html', context={'form': form})


def user_edit(request):
    id = request.GET.get('id')
    user = User.objects.filter(id=id).first()
    if request.method == 'GET':
        # instance 需要回显的实例数据
        form = UserModelForm(instance=user)
        return render(request, 'user/user_edit.html', context={'form': form})
    #  更新用户信息  instance=user  没有这个参数 则做的添加数据
    form = UserModelForm(data=request.POST, instance=user)
    if form.is_valid():
        form.save()
        return redirect(reverse('user_list'))
    return render(request, 'user/user_edit.html', context={'form': form})


def user_delete(request, id):
    User.objects.filter(id=id).delete()
    return redirect(reverse('user_list'))


# 重置密码
def user_pwd_reset(request, id):
    User.objects.filter(id=id).update(password=hashlib.md5('111111'.encode('utf-8')).hexdigest())
    return redirect(reverse('user_list'))


# 员工列表   分页数据
def emp_list(request):
    emp_list = Emp.objects.all().order_by('-id')
    context = page_utile(request, emp_list)
    return render(request, 'emp/emp_list.html', context=context)


# 编辑员工信息
def emp_edit(request, id):
    emp = Emp.objects.filter(id=id).first()
    if request.method == 'GET':
        #  设置入职时间的格式   2025-05-16T14:33
        emp.hire_date = emp.hire_date.strftime('%Y-%m-%dT%H:%M')
        form = EmpModelForm(instance=emp)
        return render(request, 'emp/emp_edit.html', context={'form': form})

    form = EmpModelForm(data=request.POST, instance=emp)
    if form.is_valid():
        form.save()
        return redirect(reverse('emp_list'))
    return render(request, 'emp/emp_edit.html', context={'form': form})


def emp_delete(request, id):
    emp = Emp.objects.filter(id=id).delete()
    return redirect(reverse('emp_list'))


# 新增员工信息
def emp_add(request):
    if request.method == 'GET':
        form = EmpModelForm()
        return render(request, 'emp/emp_add.html', context={'form': form})

    form = EmpModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(reverse('emp_list'))
    return render(request, 'emp/emp_add.html', context={'form': form})


# 用户认证
def user_login(request):
    if request.method == 'GET':
        return render(request, 'login/login.html')

    username = request.POST.get('username')
    password = request.POST.get('password')  # 明文  123456
    # 摘要算法
    password = hashlib.md5(password.encode('utf-8')).hexdigest()

    # 根据用户名和密码查询用户信息
    user = User.objects.filter(username=username, password=password).first()
    if user is None:
        return render(request, 'login/login.html', context={'info': '用户名或密码错误'})

    # 登录成功  进入后台  保存用户信息在session对象中 会话的保持    实现数据共享  /user/list  A  B   cookie  -> session 容器
    request.session['user_id'] = user.id
    request.session['username'] = user.username
    # 标识用户是否认证
    request.session['is_auth'] = True
    return redirect(reverse('echarts_page'))


# 退出用户
def user_logout(request):
    # 销毁用户在服务端保存的session中值
    # request.session.clear()
    # 删除session
    request.session.flush()
    return redirect(reverse('user_login'))


# 用户密码修改
def user_personal_pwd(request):
    if request.method == 'GET':
        return render(request, 'user/user_pwd.html')

    # 获取密码 原始密码
    old_pwd = request.POST.get("old_pwd")  # 111111
    # 判定原始密码是否正确
    user_id = request.session['user_id']
    user = User.objects.filter(id=user_id).first()
    if user.password != hashlib.md5(old_pwd.encode('utf-8')).hexdigest():
        return render(request, 'user/user_pwd.html', context={'message': '原始密码不正确'})
    # 获取新密码
    new_pwd = request.POST.get('new_pwd')
    # 更新密码
    User.objects.filter(id=user_id).update(password=hashlib.md5(new_pwd.encode('utf-8')).hexdigest())
    # 密码修改成功  跳转登录页  重新登录
    return redirect(reverse('user_logout'))


# 权限判定
def permission(request):
    return render(request, 'permission/permission_403.html')


# 数据分析请求处理
def echarts_list(request):
    return render(request, 'echarts/echarts.html')


from django.db import connection  # 导入连接对象


def echarts_emp_age_avg(request):
    # 获取员工年龄的平均值
    sql = "SELECT AVG(age) AS age  FROM  emp"
    context = {"code": 200}
    with connection.cursor() as cursor:
        cursor.execute(sql)
        data = cursor.fetchone()
        avg_age = int(data[0])
        context['avg_age'] = avg_age
    return HttpResponse(json.dumps(context), content_type='application/json')


def echarts_emp_pie(request):
    sql = """
            SELECT department.name  AS `name`  ,COUNT(emp.id) AS `value`
        FROM  emp  JOIN department  ON emp.department_id = department.id
        GROUP BY emp.department_id
    """
    context = {"code": 200}
    with connection.cursor() as cursor:
        cursor.execute(sql)
        data = cursor.fetchall()
        context['data'] = dict(data)
    return HttpResponse(json.dumps(context), content_type='application/json')


def ajax_page(request):
    return render(request, 'ajax/ajax.html')


def ajax_username(request):
    # 阻塞5s
    # time.sleep(5)
    """
        if request.method == 'GET':
        username = request.GET.get('username')
        if username == 'admin':
            # 用户名存在   {code：110,message:'用户名已存在',data:obj}
            context = {'code': 110, 'message': '用户名已存在'}
            return HttpResponse(json.dumps(context), content_type='application/json')
        else:
            context = {'code': 200, 'message': '用户名可用'}
            return HttpResponse(json.dumps(context), content_type='application/json')
    """
    user = json.loads(request.body.decode('utf-8'))
    print(user)
    if user.get('username') == 'admin':
        # 用户名存在   {code：110,message:'用户名已存在',data:obj}
        context = {'code': 110, 'message': '用户名已存在'}
        return HttpResponse(json.dumps(context), content_type='application/json')
    else:
        context = {'code': 200, 'message': '用户名可用'}
        return HttpResponse(json.dumps(context), content_type='application/json')
